import com.mysql.jdbc.Connection;
import lombok.Getter;
import lombok.SneakyThrows;
import utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/message/add")
public class AddMessageServlet extends HttpServlet {
    public  static  List<Message> msgList=new ArrayList<>();
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int result=-1;
        //得到有效参数
         String from=req.getParameter("from");
         String to=req.getParameter("to");
         String msg=req.getParameter("msg");
         if(!StringUtils.hasLength(from)&&StringUtils.hasLength(to)&&StringUtils.hasLength(msg)){
             //2将表白对象加入集合中
             //2.1得到Connect
             Connection connection= DBUtils.getConnection();

             //2.2拼接SQL创建执行器
             String sql="insert into message('from','to','msg') values(?,?,?)";
             PreparedStatement statement=connection.prepareStatement(sql);
             statement.setString(1,from);
             statement.setString(2,to);
             statement.setString(3,msg);
             AddMessageServlet.msgList.add(new Message(from,to,msg));
             result=1;
         }
         resp.setContentType("text/html;charset=utf-8");
         resp.getWriter().println(result);
    }

}
@Getter
class Message{
    private String from;
    private String to;
    private String msg;
    public Message(String from,String to,String msg){
  this.from=from;
  this.msg=msg;
  this.to=to;
    }
}
